<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col
              :md="5"
              :sm="16">
              <a-form-item label="合同名称">
                <a-input
                  v-model="queryParam.contractName"
                  placeholder="请输入合同名称" />
              </a-form-item>
            </a-col>
            <a-col
              :md="5"
              :sm="16">
              <a-form-item label="甲方经办人">
                <a-input
                  v-model="queryParam.otherHandler"
                  placeholder="请输入甲方经办人" />
              </a-form-item>
            </a-col>
            <a-col
              :md="5"
              :sm="16">
              <a-form-item label="我方经办人">
                <a-input
                  v-model="queryParam.ownerHandler"
                  placeholder="请输入我方经办人" />
              </a-form-item>
            </a-col>
            <a-col
              :md="5"
              :sm="16">
              <a-form-item label="合同类型">
                <a-select
                  v-model="queryParam.contractType"
                  placeholder="请选择">
                  <a-select-option value="1">项目合同</a-select-option>
                  <a-select-option value="2">采购合同</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="4"
              :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button
                  type="primary"
                  v-if="list"
                  @click="$refs.table.refresh(true)">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  v-if="list"
                  @click="() => {this.queryParam = {};this.$refs.table.refresh() }">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!--
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div> -->
      <div>
        <a-spin :spinning="tableLoading">
          <s-table
            ref="table"
            size="default"
            rowKey="incomeId"
            :columns="incomeExpensesColumns"
            :data="loadData"
            showPagination="auto"
            :customRow="tableCustomRow">
            <span
              slot="serial"
              slot-scope="text, record, index">
              {{ index + 1 }}
            </span>
            <span
              slot="action"
              slot-scope="text, record">
              <template>
                <a
                  @click="handleEdit(record)"
                  v-if="record.parentId && update">配置</a>
                <a-divider type="vertical" v-if="record.parentId && update" />
                <a
                  @click="handleAdd(record)"
                  v-if="!record.parentId && save">新增实际收支</a>
                <a-divider type="vertical" v-if="!record.parentId" />
                <a
                  @click="handleDetail(record)"
                  v-show="detail"
                  v-if="!record.parentId">详情</a>
                <a-divider type="vertical" v-if="record.parentId || !record.children" />
                <a
                  @click="handleDelete(record)"
                  v-show="deleteBtn"
                  v-if="record.parentId || !record.children">删除</a>
              </template>
            </span>
          </s-table>
        </a-spin>
      </div>
      <div
        class="table-operator"
        :style="{marginTop: '30px'}"
        v-show="files">
        <span style="font-size: 20px;font-weight: bold;padding: 10px;padding-right: 30px">附件</span>
        <a-button
          type="primary"
          icon="plus"
          v-if="fupdate"
          @click="addFile">新建</a-button>
        <a-spin :spinning="fileTabLoading">
          <a-table
            ref="fileTable"
            size="default"
            rowKey="fileId"
            :style="{marginTop: '50px'}"
            :columns="fileColumns"
            :dataSource="files"
            :pagination="false">
            <span
              slot="serial"
              slot-scope="text, record, index">
              {{ index + 1 }}
            </span>
            <span
              slot="fileDownload"
              slot-scope="text, record">
              <a
                :href="`${record.fileUrl}`"
                :download="record.fileName">{{ record.fileName }}</a>
            </span>
            <span
              slot="action"
              slot-scope="text, record">
              <template>
                <a
                  @click="handleShowImg(record)">预览</a>
                <a-divider type="vertical" />
                <a
                  v-if="fdeleteBtn"
                  @click="handleDeteleFile(record)">删除</a>
              </template>
            </span>
          </a-table>
        </a-spin>
      </div>
      <a-modal
        title="图片预览"
        width="800"
        :visible="showImg"
        :footer="null"
        @cancel="() => {this.showImg = false}">
        <div style="display: flex;justify-content: center">
          <img style="width: 700px" :src="imgUrl" />
        </div>
      </a-modal>
      <file-create-form
        ref="fileCreateForm"
        :visible="fileCreateVisible"
        @cancel="handleFileCancel"
        @ok="handleFileOK" />
      <create-form
        ref="createModal"
        :fsave="fsave"
        :visible="visible"
        :loading="confirmLoading"
        :isEdit="isEdit"
        @cancel="handleCancel"
        @ok="handleOk" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable, Ellipsis } from '@/components'
// deleteIncomeReq
import { getIncomeList, getFileByIds, saveIncome, updateIncome, deleteIncomeReq } from '@/api/manage'
import { Modal } from 'ant-design-vue'
import CreateForm from './modules/CreateForm'
import { incomeExpensesColumns, fileColumns, childColumns } from './config'
import FileCreateForm from './modules/FileCreateForm'
import { isInMenu } from '../config.js'
import { mapGetters } from 'vuex'

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    FileCreateForm
  },
  data () {
    this.incomeExpensesColumns = incomeExpensesColumns
    this.childColumns = childColumns
    this.fileColumns = fileColumns
    return {
      showImg: false,
      imgUrl: '',
      // 权限参数
      list: false, // 列表
      save: false, // 加
      deleteBtn: false, // 删
      update: false, // 改
      detail: false,

      flist: false, // 列表
      fsave: false, // 加
      fdeleteBtn: false, // 删
      fupdate: false, // 改
      // create model
      visible: false,
      confirmLoading: false,
      isAdd: false,
      isEdit: false,
      incomeList: undefined,
      pagination: undefined,
      // 高级搜索 展开/关闭
      tableLoading: false,
      advanced: false,
      fileTabLoading: false,
      // 查询参数
      queryParam: {},
      files: undefined,
      fileCreateVisible: false,
      // 新增和配置时保存的记录
      conRecord: undefined,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = { page: parameter.pageNo, limit: parameter.pageSize }
        const param = Object.assign({}, this.queryParam)
        return (
          this.list &&
          getIncomeList(Object.assign({}, param, requestParameters, { entryDate: undefined })).then(res => {
            return Object.assign({}, res, {
              totalCount: res.total,
              pageNo: parameter.pageNo,
              pageSize: parameter.pageSize
            })
          })
        )
      },
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null
    }
  },
  created () {
    // 点击查看
    this.list = isInMenu(this.menu, 'ROLE_but:income:list') && isInMenu(this.menu, 'ROLE_but:income:info')
    // 增加
    this.save = isInMenu(this.menu, 'ROLE_but:income:save')
    // 改
    this.update = isInMenu(this.menu, 'ROLE_but:income:update')
    // 删除
    this.deleteBtn = isInMenu(this.menu, 'ROLE_but:income:delete')
    this.detail = isInMenu(this.menu, 'ROLE_but:planIncome:contractInfo')

    // 点击查看
    this.flist = isInMenu(this.menu, 'ROLE_but:incomeFile:ids')
    // 增加
    this.fsave = isInMenu(this.menu, 'ROLE_but:incomeFile:save')
    // 改
    this.fupdate = isInMenu(this.menu, 'ROLE_but:incomeFile:update')
    // 删除
    this.fdeleteBtn = isInMenu(this.menu, 'ROLE_but:incomeFile:delete')
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleShowImg (record) {
      this.showImg = true
      this.imgUrl = record?.fileUrl
    },
    handleDetail (record) {
      this.$router.push({
        name: 'contractInfo',
        path: '/contract/contractInfo',
        query: {
          record: JSON.stringify(record)
        }
      })
    },
    handleFileOK () {
      const form = this.$refs.fileCreateForm.form
      form.validateFields((errors, values) => {
        if (!errors && values.fileIds) {
          const _fileIds = this.conRecord.fileIds ? this.conRecord.fileIds + ',' : ''
          const params = {
            fileIds: _fileIds + values.fileIds,
            incomeId: this.conRecord.incomeId,
            otherHandler: this.conRecord.otherHandler,
            ownerHandler: this.conRecord.ownerHandler,
            payMoment: this.conRecord.payMoment,
            amount: this.conRecord.amount,
            contractId: this.conRecord.contractId,
            bankName: this.conRecord.bankName,
            bankAccountName: this.conRecord.bankAccountName,
            bankAccount: this.conRecord.bankAccount
          }
          // 实际收支附件更改
          if (this.conRecord.parentId !== null) {
            updateIncome(params)
              .then(res => {
                this.$refs.table.refresh()
              })
              .finally(() => {
                this.fileCreateVisible = false
                this.$refs.createModal.resetFileList()
                this.conRecord.fileIds = _fileIds + values.fileIds
                this.getFiles({ fileIds: _fileIds + values.fileIds })
              })
          } else {
            // 合同附件更改
            updateIncome(Object.assign(params, { parentId: this.conRecord.parentId }))
              .then(res => {
                this.$refs.table.refresh()
              })
              .finally(() => {
                this.fileCreateVisible = false
                this.$refs.createModal.resetFileList()
                this.conRecord.fileIds = _fileIds + values.fileIds
                this.getFiles({ fileIds: _fileIds + values.fileIds })
              })
          }
        }
      })
    },
    handleDeteleFile (record) {
      let _fileIds = ''
      if (this.conRecord.fileIds) {
        const fids = this.conRecord.fileIds.split(',')
        const index = fids.indexOf(String(record.fileId))
        if (index > -1) {
          fids.splice(index, 1)
        }
        _fileIds = fids.join(',') || ''
        this.conRecord.fileIds = _fileIds
      }
      const params = {
        fileIds: _fileIds,
        incomeId: this.conRecord.incomeId,
        otherHandler: this.conRecord.otherHandler,
        ownerHandler: this.conRecord.ownerHandler,
        payMoment: this.conRecord.payMoment,
        amount: this.conRecord.amount,
        contractId: this.conRecord.contractId,
        bankName: this.conRecord.bankName,
        bankAccountName: this.conRecord.bankAccountName,
        bankAccount: this.conRecord.bankAccount
      }
      // 实际收支附件更改
      if (this.conRecord.parentId !== null) {
        updateIncome(params)
          .then(res => {
            this.$refs.table.refresh()
          })
          .finally(() => {
            this.fileCreateVisible = false
            this.$refs.createModal.resetFileList()
            this.conRecord.fileIds = _fileIds
            this.getFiles({ fileIds: _fileIds })
          })
      } else {
        // 合同附件更改
        updateIncome(Object.assign(params, { parentId: this.conRecord.parentId }))
          .then(res => {
            this.$refs.table.refresh()
          })
          .finally(() => {
            this.fileCreateVisible = false
            this.$refs.createModal.resetFileList()
            this.conRecord.fileIds = _fileIds
            this.getFiles({ fileIds: _fileIds })
          })
      }
    },
    handleFileCancel () {
      this.$refs.fileCreateForm.resetFileList()
      this.fileCreateVisible = false
    },
    addFile () {
      this.$refs.fileCreateForm.resetFileList()
      this.fileCreateVisible = true
    },
    getFiles (record) {
      this.fileTabLoading = true
      getFileByIds({ fileIds: record.fileIds })
        .then(res => {
          this.files = res.data
        })
        .finally(() => {
          this.fileTabLoading = false
        })
    },
    handleAdd (record) {
      this.visible = true
      this.isAdd = true
      this.isEdit = false
      const form = this.$refs.createModal.form
      form.resetFields()
      this.conRecord = record
      this.$nextTick(() => {
        form.setFieldsValue({
          contractName: record.contractName,
          otherHandler: record.otherHandler,
          ownerHandler: record.ownerHandler
        })
      })
    },
    handleEdit (record) {
      this.visible = true
      this.isEdit = true
      this.isAdd = false
      const form = this.$refs.createModal.form
      this.conRecord = record
      this.$nextTick(() => {
        form.setFieldsValue(record)
      })
    },
    handleDelete (record) {
      Modal.confirm({
        title: '是否确认删除',
        content: '删除后数据不可恢复',
        onOk: () => {
          this.tableLoading = true
          deleteIncomeReq({ incomeId: record.incomeId }).finally(() => {
            this.$refs.table.refresh()
            this.tableLoading = false
          })
        }
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.payMoment instanceof Array && values.payMoment.length > 1) {
            this.$message.error('付款阶段只允许选一个')
            this.confirmLoading = false
            return null
          }
          if (values.payMoment instanceof Array) {
            values.payMoment = values.payMoment[0]
          }
          if (this.isAdd) {
            saveIncome(
              Object.assign({}, values, { contractId: this.conRecord.contractId, parentId: this.conRecord.incomeId })
            )
              .then(res => {
                this.$refs.table.refresh()
              })
              .finally(() => {
                this.visible = false
                this.$refs.createModal.resetFileList()
                this.confirmLoading = false
              })
          } else if (this.isEdit) {
            updateIncome(
              Object.assign({}, values, {
                contractId: this.conRecord.contractId,
                incomeId: this.conRecord.incomeId,
                fileIds: this.conRecord.fileIds,
                parentId: this.conRecord.parentId
              })
            )
              .then(res => {
                this.$refs.table.refresh()
              })
              .finally(() => {
                this.visible = false
                this.$refs.createModal.resetFileList()
                this.confirmLoading = false
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    tableCustomRow (record, index) {
      return {
        style: {
          'background-color': record.incomeId === this.physicalSurveyCurrRowId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.physicalSurveyCurrRowId = record.incomeId
            // this.custom = record
            this.conRecord = record
            // 附件为空不请求
            if (record.fileIds) { this.flist && this.getFiles(record) } else {
              this.files = []
            }
          }
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
& /deep/ .ant-table-row-level-1 {
  background-color: #fafaff;
}
</style>
